import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getRecords,
  getRecordDetail,
  deleteRecord,
  batchDeleteRecords,
  updateRecordTags,
  updateAdminNotes,
  getAdminMessages,
} from '@/api/records'

export const useQueryRecordStore = defineStore('queryRecord', () => {
  // 状态
  const records = ref([])
  const totalRecords = ref(0)
  const loading = ref(false)
  const currentRecord = ref(null)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const error = ref(null)
  const lastUpdate = ref(null)

  // 筛选条件
  const filters = ref({
    timeRange: [],
    keyword: '',
    status: [],
    userId: '',
    datasetId: '',
    modelId: '',
    tags: [],
    quickTimeFilter: '',
  })

  // 排序
  const sortBy = ref('timestamp')
  const sortDesc = ref(true)

  // 选中的记录
  const selectedRecordIds = ref([])

  // 获取记录列表
  const fetchRecords = async (params = {}) => {
    loading.value = true
    records.value = []
    error.value = null

    try {
      const apiParams = {
        ...constructFilterParams(),
        page: currentPage.value,
        page_size: pageSize.value,
        sortBy: sortBy.value,
        sortDesc: sortDesc.value ? 'desc' : 'asc',
        ...params,
      }

      const response = await getRecords(apiParams)
      records.value = response.records
      totalRecords.value = response.total
      lastUpdate.value = new Date()
    } catch (err) {
      console.error('获取会话失败', err)
      ElMessage.error('获取会话失败')
      records.value = []
      error.value = err
    } finally {
      loading.value = false
    }
  }

  // 获取单条记录详情
  const fetchRecordById = async (id) => {
    loading.value = true
    currentRecord.value = null

    try {
      const response = await getRecordDetail(id)
      currentRecord.value = response
    } catch (error) {
      console.error('获取会话详情失败', error)
      ElMessage.error('获取会话详情失败')
    } finally {
      loading.value = false
    }
  }

  // 删除记录
  const deleteRecordById = async (id) => {
    loading.value = true

    try {
      await deleteRecord(id)
      // 从本地数据中移除
      records.value = records.value.filter((record) => record.id !== id)
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除会话失败', error)
      ElMessage.error('删除会话失败')
    } finally {
      loading.value = false
    }
  }

  // 批量删除记录
  const batchDeleteRecordsById = async (ids) => {
    loading.value = true

    try {
      await batchDeleteRecords(ids)
      // 从本地数据中移除
      records.value = records.value.filter((record) => !ids.includes(record.id))
      ElMessage.success('批量删除成功')
    } catch (error) {
      console.error('批量删除会话失败', error)
      ElMessage.error('批量删除会话失败')
    } finally {
      loading.value = false
    }
  }

  // 更新记录标签
  const updateRecordTagsById = async (id, tags) => {
    try {
      const response = await updateRecordTags(id, tags)

      // 更新当前记录和列表中的记录
      if (currentRecord.value && currentRecord.value.id === id) {
        currentRecord.value.tags = tags
      }

      const index = records.value.findIndex((record) => record.id === id)
      if (index !== -1) {
        records.value[index].tags = tags
      }

      ElMessage.success('标签更新成功')
      return response
    } catch (error) {
      console.error('更新标签失败', error)
      ElMessage.error('更新标签失败')
      throw error
    }
  }

  // 更新管理员备注
  const updateAdminNotesById = async (id, notes) => {
    try {
      const response = await updateAdminNotes(id, notes)

      // 更新当前记录和列表中的记录
      if (currentRecord.value && currentRecord.value.id === id) {
        currentRecord.value.admin_notes = notes
      }

      const index = records.value.findIndex((record) => record.id === id)
      if (index !== -1) {
        records.value[index].admin_notes = notes
      }

      ElMessage.success('备注更新成功')
      return response
    } catch (error) {
      console.error('更新备注失败', error)
      ElMessage.error('更新备注失败')
      throw error
    }
  }

  // 获取管理员消息列表
  const fetchAdminMessages = async (params = {}) => {
    loading.value = true
    try {
      const response = await getAdminMessages(params)
      return {
        data: response.data,
        total: response.total,
        page: response.page,
        pageSize: response.page_size,
        totalPages: response.total_pages,
      }
    } catch (error) {
      console.error('获取管理员消息列表失败', error)
      ElMessage.error('获取管理员消息列表失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 构建筛选参数
  const constructFilterParams = () => {
    const params = {}

    // 时间范围处理
    if (filters.value.timeRange && filters.value.timeRange.length === 2) {
      params.startTime = filters.value.timeRange[0]
      params.endTime = filters.value.timeRange[1]
    }

    // 快速时间筛选
    if (filters.value.quickTimeFilter) {
      // 根据快速筛选设置时间范围
      const now = new Date()
      let startTime = new Date()
      let day = 0

      switch (filters.value.quickTimeFilter) {
        case 'today':
          startTime.setHours(0, 0, 0, 0)
          break
        case 'yesterday':
          startTime.setDate(startTime.getDate() - 1)
          startTime.setHours(0, 0, 0, 0)
          now.setDate(now.getDate() - 1)
          now.setHours(23, 59, 59, 999)
          break
        case 'thisWeek':
          day = startTime.getDay() || 7
          startTime.setDate(startTime.getDate() - day + 1)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'thisMonth':
          startTime.setDate(1)
          startTime.setHours(0, 0, 0, 0)
          break
      }

      params.startTime = startTime.toISOString()

      if (filters.value.quickTimeFilter === 'yesterday') {
        params.endTime = now.toISOString()
      }
    }

    // 其他筛选条件处理
    if (filters.value.keyword) params.keyword = filters.value.keyword
    if (filters.value.status && filters.value.status.length)
      params.status = filters.value.status.join(',')
    if (filters.value.userId) params.userId = filters.value.userId
    if (filters.value.datasetId) params.datasetId = filters.value.datasetId
    if (filters.value.modelId) params.modelId = filters.value.modelId
    if (filters.value.tags && filters.value.tags.length) params.tags = filters.value.tags.join(',')

    return params
  }

  // 设置筛选条件并重新加载数据
  const setFilters = async (newFilters) => {
    filters.value = { ...filters.value, ...newFilters }
    // 重置到第一页
    currentPage.value = 1
    return await fetchRecords()
  }

  // 设置快速时间筛选
  const setQuickTimeFilter = async (filter) => {
    filters.value.quickTimeFilter = filter
    // 清除手动设置的时间范围
    filters.value.timeRange = []
    // 重置到第一页
    currentPage.value = 1
    return await fetchRecords()
  }

  // 设置排序
  const setSorting = async (field, descending = true) => {
    sortBy.value = field
    sortDesc.value = descending
    return await fetchRecords()
  }

  // 设置分页
  const setPage = async (page) => {
    currentPage.value = page
    return await fetchRecords()
  }

  // 设置每页条数
  const setPageSize = async (size) => {
    pageSize.value = size
    // 重置到第一页
    currentPage.value = 1
    return await fetchRecords()
  }

  // 计算属性
  const totalPages = computed(() => Math.ceil(totalRecords.value / pageSize.value))
  const isAllSelected = computed(
    () =>
      selectedRecordIds.value.length > 0 && selectedRecordIds.value.length === records.value.length,
  )
  const isPartiallySelected = computed(
    () =>
      selectedRecordIds.value.length > 0 && selectedRecordIds.value.length < records.value.length,
  )

  // 选择/取消选择全部
  const toggleSelectAll = () => {
    if (isAllSelected.value) {
      selectedRecordIds.value = []
    } else {
      selectedRecordIds.value = records.value.map((record) => record.id)
    }
  }

  // 选择/取消选择单个记录
  const toggleSelect = (id) => {
    const index = selectedRecordIds.value.indexOf(id)
    if (index === -1) {
      selectedRecordIds.value.push(id)
    } else {
      selectedRecordIds.value.splice(index, 1)
    }
  }

  // 清除所有筛选条件
  const clearFilters = () => {
    filters.value = {
      timeRange: [],
      keyword: '',
      status: [],
      userId: '',
      datasetId: '',
      modelId: '',
      tags: [],
      quickTimeFilter: '',
    }
  }

  // 重置状态
  const reset = () => {
    records.value = []
    totalRecords.value = 0
    currentRecord.value = null
    currentPage.value = 1
    selectedRecordIds.value = []
    clearFilters()
  }

  return {
    // 状态
    records,
    totalRecords,
    loading,
    currentRecord,
    currentPage,
    pageSize,
    filters,
    sortBy,
    sortDesc,
    selectedRecordIds,
    error,
    lastUpdate,

    // 计算属性
    totalPages,
    isAllSelected,
    isPartiallySelected,

    // 操作方法
    fetchRecords,
    fetchRecordById,
    deleteRecord: deleteRecordById,
    batchDeleteRecords: batchDeleteRecordsById,
    updateRecordTags: updateRecordTagsById,
    updateAdminNotes: updateAdminNotesById,
    getAdminMessages: fetchAdminMessages,
    setFilters,
    setQuickTimeFilter,
    setSorting,
    setPage,
    setPageSize,
    toggleSelectAll,
    toggleSelect,
    clearFilters,
    reset,
  }
})
